package com.pureut.production.service.impl;


import com.alibaba.fastjson2.JSON;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.equipment.api.FeignEquipmentService;
import com.pureut.production.domain.GroupManagement;
import com.pureut.production.domain.GroupManagementDetail;
import com.pureut.production.domain.SpunlaceOutputDetail;
import com.pureut.production.domain.dto.*;
import com.pureut.production.domain.dto.quality.BadMonthDto;
import com.pureut.production.domain.dto.quality.YieldDto;
import com.pureut.production.domain.vo.GroupVo;
import com.pureut.production.mapper.*;
import com.pureut.production.service.KanBanService;
import com.pureut.system.api.QualityFeginService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 水刺看板Service
 *
 * @author: CM
 * @date: 2023/5/4  15:26
 */

@Service
public class KanBanServiceImpl implements KanBanService {

    //班组管理mapper
    @Resource
    private GroupManagementMapper groupManagementMapper;

    @Resource
    private GroupManagementDetailMapper groupManagementDetailMapper;

    //线边库存Mapper
    @Resource
    private LineStockMapper lineStockMapper;


    //水刺制令单Mapper
    @Resource
    private SpunlaceOrderMapper spunlaceOrderMapper;

    //水刺产出Mapper
    @Resource
    private SpunlaceOutputMapper spunlaceOutputMapper;

    //水刺产出明细Mapper
    @Resource
    private SpunlaceOutputDetailMapper spunlaceOutputDetailMapper;

    @Resource
    private QualityFeginService qualityFeginService;

    @Resource
    private FeignEquipmentService feignEquipmentService;

    /**
     * 查询车间信息
     *
     * @param lineCode
     * @return
     */
    @Override
    public WorkshopInfoDto getWorkshopInfo(String lineCode) {

        //通过线别id查出工厂日历班组id集合
        List<GroupManagementDetail> groupManagementDetailList = groupManagementDetailMapper.getWorkCalendar(lineCode);

        Long groupId = 0L;

        for (GroupManagementDetail groupManagementDetail : groupManagementDetailList) {
            GroupVo groupVo = new GroupVo();
            groupVo.setCalendarId(groupManagementDetail.getGroupCalendarId());
            groupVo.setTeamId(groupManagementDetail.getGroupCalendarTeam());
            GroupManagementDetailViewDto groupManagementDetailViewDto = groupManagementDetailMapper.selectCalendar(groupVo);
            Date startTime = groupManagementDetailViewDto.getStartTime();
            Date endTime = groupManagementDetailViewDto.getEndTime();

            Date nowTime = new Date();
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(nowTime);
//            Date time = calendar.getTime();
            //判断当前时间是否在开始时间和结束时间之内
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
            String time2 = simpleDateFormat.format(nowTime);
            String timeStart = simpleDateFormat.format(startTime);
            String timeEnd = simpleDateFormat.format(endTime);
            //如果在开始时间和结束时间之间
            if (time2.compareTo(timeStart) > 0 && time2.compareTo(timeEnd) < 0) {
                groupId = groupManagementDetail.getGroupId();
                break;
            }
        }
        WorkshopInfoDto workshopInfo = groupManagementMapper.getWorkshopInfo(lineCode, groupId);
        return workshopInfo;
    }

    /**
     * 线边库存情况
     *
     * @param lineCode
     * @return
     */
    @Override
    public List<LineStockInfoDto> getLineStockInfo(String lineCode) {
        return lineStockMapper.getLineStockInfo(lineCode);
    }

    /**
     * 水刺看板-制令单（生产中）
     *
     * @param lineCode
     * @return
     */
    @Override
    public ManufacturingOrderDto getManufacturingOrder(String lineCode) {
        ManufacturingOrderDto manufacturingOrderDto = spunlaceOrderMapper.getSpunlaceOrderInfo(lineCode);

        if (manufacturingOrderDto == null) {
            return manufacturingOrderDto;

        }


        //查询最后一条水刺产出的跨天时间
        SpunlaceOutputDetail spunlaceOutputDetail = spunlaceOutputDetailMapper.selectOutputDateTime(manufacturingOrderDto.getSpunlaceOrderNumber());


        if (spunlaceOutputDetail == null) {
            return manufacturingOrderDto;

        } else {
            //分组查询每个班次的产量
            List<ManufacturingOrderDto> listGroupBy = spunlaceOutputDetailMapper.groupByClassWeight(manufacturingOrderDto.getSpunlaceOrderNumber());

            if (listGroupBy.size() == 0) {
                manufacturingOrderDto.setProductionThisShift("0");
                manufacturingOrderDto.setProductionPerShift("0");
                manufacturingOrderDto.setPerClass("");
                manufacturingOrderDto.setThisClass("");
            } else {
                for (int i = 0; i < listGroupBy.size(); i++) {
                    if (i == 0) {
                        manufacturingOrderDto.setProductionThisShift(listGroupBy.get(0).getProductionThisShift());
                        manufacturingOrderDto.setThisClass(listGroupBy.get(0).getThisClass());
                    }
                    if (i == 1) {
                        manufacturingOrderDto.setProductionPerShift(listGroupBy.get(1).getProductionThisShift());
                        manufacturingOrderDto.setPerClass(listGroupBy.get(0).getThisClass());
                        break;
                    } else {
                        manufacturingOrderDto.setProductionPerShift("0");
                        manufacturingOrderDto.setPerClass("");
                    }
                }
            }

            //查出A,B班分别产出了多少重量
            ManufacturingOrderDto manufacturingOrderDto1 = spunlaceOutputDetailMapper.selectGroupByWeight(manufacturingOrderDto.getSpunlaceOrderNumber());
            manufacturingOrderDto.setClassA(manufacturingOrderDto1.getClassA());
            manufacturingOrderDto.setClassB(manufacturingOrderDto1.getClassB());

            long nh = 1000 * 60 * 60;// 一小时的毫秒数
            Date date = new Date();
            long diff = date.getTime() - spunlaceOutputDetail.getCreateTime().getTime();
            // 计算差多少小时
            BigDecimal bigDecimal = new BigDecimal(String.valueOf(diff));
            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(nh));
            BigDecimal divide = bigDecimal.divide(bigDecimal1, 2, BigDecimal.ROUND_HALF_UP);
            manufacturingOrderDto.setProductionDuration(divide.toString());

            //查询产出数量
            long productionCount = spunlaceOutputDetailMapper.selectProductionCount(manufacturingOrderDto.getSpunlaceOrderNumber());
            manufacturingOrderDto.setProductionCount(productionCount);

            return manufacturingOrderDto;
        }
    }

    /**
     * 生产看板-制令单（待上线）
     *
     * @param lineCode
     * @return
     */
    @Override
    public List<ToBeOnlineDto> getToBeOnline(String lineCode) {
        return spunlaceOrderMapper.selectToBeOnline(lineCode);
    }

    /**
     * 水刺看板-班组月产量统计
     *
     * @param lineCode
     * @return
     */
    @Override
    public List<TeamsMonthDto> getTeamsMonthOutput(String lineCode) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date); // 设置为当前时间
        calendar.add(Calendar.MONTH, -1);
        date = calendar.getTime();

        //上月时间
        String lastMonth = format.format(date);

        //本月时间
        String month = format.format(new Date());

        //获取当前的班组集合
        List<GroupManagement> groupManagementList = groupManagementMapper.getGroupInfo(lineCode);

        List<TeamsMonthDto> list = new ArrayList<>();
        for (GroupManagement groupManagement : groupManagementList) {
            TeamsMonthDto teamsMonthDto = spunlaceOrderMapper.getTeamsMonthOutPut(month, lastMonth, lineCode, groupManagement.getGroupCode());
            teamsMonthDto.setClasses(groupManagement.getGroupName());
            list.add(teamsMonthDto);

        }

        return list;
    }

    /**
     * 生产看板-产线产量统计对比
     *
     * @param lineCode
     * @return
     */
    @Override
    public List<ProductionContrastDto> getProductionContrast(String lineCode) {
        //分组查出近2个月的物料料号
        List<GroupMaterialDto> groupMaterialDtoList = spunlaceOrderMapper.getGroupMaterialCode(lineCode);

        List<ProductionContrastDto> list = new ArrayList<ProductionContrastDto>();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date); // 设置为当前时间
        calendar.add(Calendar.MONTH, -1);
        date = calendar.getTime();

        //上月时间
        String lastMonth = format.format(date);

        //本月时间
        String month = format.format(new Date());

        for (GroupMaterialDto groupMaterialDto : groupMaterialDtoList) {
            //查询上个月和这个月产量
            ProductionContrastDto productionContrastDto = spunlaceOrderMapper.getMonthWeight(groupMaterialDto.getMaterialType(), lineCode, lastMonth, month);
            productionContrastDto.setMaterialType(groupMaterialDto.getCodingRules());
            list.add(productionContrastDto);
        }
        return list;
    }

    /**
     * 生产看板-设备运行情况
     *
     * @param lineCode
     * @return
     */
    @Override
    public List<DeviceOperationDto> getEquipmentOperation(String lineCode) {
        AjaxResult ajaxResult = feignEquipmentService.getDeviceCondition(lineCode);
        List<DeviceOperationDto> list = JSON.parseArray(JSON.toJSONString(ajaxResult.get("data")), DeviceOperationDto.class);
        if (list == null) {
            ArrayList<DeviceOperationDto> arrayList = new ArrayList<>();
            list = arrayList;
        }
        return list;
    }

    /**
     * 生产看板-班组近7天良品率
     *
     * @param lineCode
     * @return
     */
    @Override
    public YieldDto getTeamGoodProducts(String lineCode) {
        AjaxResult yield = qualityFeginService.getYield(lineCode);
        YieldDto yieldDto = JSON.parseObject(JSON.toJSONString(yield.get("data")), YieldDto.class);

        return yieldDto;
    }

    /**
     * 生产看板-本月不良分布
     *
     * @param lineCode
     * @return
     */
    @Override
    public List<BadMonthDto> getMonthBad(String lineCode) {
        AjaxResult ajaxResult = qualityFeginService.getBadMonth(lineCode);
        List<BadMonthDto> list = JSON.parseArray(JSON.toJSONString(ajaxResult.get("data")), BadMonthDto.class);
        return list;
    }
}
